#include <iostream>
#include <thread>
#include <chrono>
#include <cassert>

#include "mysql_conn_pool.h"


bool user_info_verify(const string &u_name, const string &u_passwd, bool is_login) {
    if (u_name.empty() || u_passwd.empty()) {
        return false;
    }

    LOG_INFO("Verifying the user with name:'%s' and pwd:'%s'.", u_name.c_str(), u_passwd.c_str());

    MySqlConn mysql_conn;
    assert(mysql_conn.get());

    bool result;
    // 查询用户及密码
//    MYSQL_FIELD *mysql_field = nullptr;
    MYSQL_RES *query_res = nullptr;
    char sql_cmd[256] = {0};
    snprintf(sql_cmd, 256, "SELECT username, password FROM users WHERE username='%s' LIMIT 1", u_name.c_str());

    LOG_DEBUG("MySql command: %s;", sql_cmd);

    if (mysql_query(mysql_conn.get(), sql_cmd) == 0) {
        query_res = mysql_store_result(mysql_conn.get());
//        unsigned int num_fields = mysql_num_fields(query_res);
//        mysql_field = mysql_fetch_field(query_res);
    } else {
        // 查询错误
        mysql_free_result(query_res);
        return false;
    }


    MYSQL_ROW row;
    while ((row = mysql_fetch_row(query_res)) != nullptr) {
        // 查询到用户名条目
        LOG_DEBUG("MYSQL ROW: %s %s", row[0], row[1]);

        string real_passwd(row[1]);
        if (is_login) {
            // 登录密码检验
            if (u_passwd == real_passwd) {
                LOG_DEBUG("Correctly verify the user named '%s'.", u_name.c_str());

                return true;
            } else {
                LOG_DEBUG("Invalid username or password.", u_name.c_str());

                return false;
            }
        }
        else {
            // 注册用户名存在
            LOG_DEBUG("The username: '%s' is unavailable!", u_name.c_str());

            return false;
        }
    }
    mysql_free_result(query_res);

    // 注册
    if (!is_login) {
        bzero(sql_cmd, 256);
        snprintf(sql_cmd, 256, "INSERT INTO users(username, password) VALUES('%s','%s')",
                 u_name.c_str(), u_passwd.c_str());
        LOG_DEBUG("MySql command: %s;", sql_cmd);

        if(mysql_query(mysql_conn.get(), sql_cmd)) {
            LOG_DEBUG("MySql INSERT error!");
            return false;
        }
        LOG_DEBUG("A new user named '%s' has been registered successfully.", u_name.c_str());
        return true;
    }

    return true;
}




int main() {
    Logger::get_instance()->init("./log", 100);
    MySqlConnPool::get_instance()->init("localhost", 3306, "srv_db", "root", "root", 10);

//    for (int i = 1; i < 500; ++i) {
//        LOG_DEBUG("log test %d: debug.",  1)
//        LOG_ERROR("log test %d: error.", 2)
//        LOG_INFO("log test %d: info.", 3)
//        LOG_WARN("log test %d: warn.", 4)
////        this_thread::sleep_for(chrono::seconds(1));
//    }


//    user_info_verify("zql", "zqlpasswd", bool(1));

    for (int i = 1; i <= 500; ++i) {
//        this_thread::sleep_for(chrono::milliseconds (5));
        thread([=](){
            uint32_t seed = time(nullptr) ^ (i << 16);

            int idx = rand_r(&seed) % 10 + 1;
            string uname = "uname" + to_string(idx);
            string passwd = "passwd" + to_string(idx);

            uint32_t is_login = rand_r(&seed) % 2;
            user_info_verify(uname, passwd, bool(is_login));
//            printf("%d, %d\n", idx, is_login);
        }).detach();
    }

//    MYSQL *sql_conn = MySqlConnPool::get_instance()->get_connection();




    this_thread::sleep_for(chrono::seconds(5));
    Logger::get_instance()->close();
    MySqlConnPool::get_instance()->close_pool();
    return 0;
}